package com.example.common.utils;

import com.example.common.exception.BaseException;
import com.example.common.utils.SpringUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


/**
 * @author DestinyCc
 * @date 2022/4/17
 */
@Component
@Slf4j
public class GithubApiUtils implements CommandLineRunner {
    @Value("${github.authorization}")
    public String authorization;

    public static String ACCESS_TOKEN;

    public static Object callGithubApi(String requestUrl){
        HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.add("Authorization", "token " + ACCESS_TOKEN);
        log.info(headers.getFirst("Authorization"));
        HttpEntity entity = new HttpEntity(headers);
        RestTemplate restTemplate = SpringUtils.getBean(RestTemplate.class);
        try {
            ResponseEntity response = restTemplate.exchange(requestUrl, HttpMethod.GET, entity, Object.class);
            return response.getBody();
        }catch (Exception e){
            throw new BaseException(e.getMessage());
        }
    }

    @Override
    public void run(String... args) throws Exception {
        ACCESS_TOKEN = authorization;
    }
}
